<?php

namespace App\Models\CacheModel\zl2;

use app\common\lib\Util;
use App\Models\Api\BaseCache;
use App\Models\Api\Recode;
use App\Models\Api\User;
use think\Cache;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl2AstrFortuneArticle extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl2_astr_fortune_article';

    protected $cacheModel = 'astro_fortune.article';

    /**
     * 发布 星运内容 动态
     * @param array $data
     * @return int|string
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['pid'])->listAdd([$id => $id]);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_list', $data['uid'])->listAdd([$id => $id], 0, 'user_list');
        }
        catch (\Exception $e)
        {
            Log::write('Zl2AstrFortuneArticle model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            $id = 0;
        }

        return (int)$id;
    }

    /**
     * 更新 星运内容 动态详情
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data)
    {
        try
        {
            // 更新数据
            $this->where(['id' => $id])->update($data);
            // 更新缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl2AstrFortuneArticle model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids], 'status' => 0];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['pid' => $type[0], 'status' => 0, 'is_hide' => 0];
        }
        $field = 'is_hide,status,uid,title,photos,pid,read_num,comment_num,zan_num,zan_num2,extend,create_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'is_hide', 'uid', 'status', 'pid', 'read_num', 'comment_num', 'zan_num', 'zan_num2', 'create_time']);

            if (isset($itemData['photos']))
            {
                $data[$index]['photos'] = json_decode($itemData['photos'], true);
            }

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 更新 星座讨论 相关信息
     * @param array $articleInfo 问答问题信息
     *      [   问题信息内 需包含字段
     *          'id'    问题ID
     *          'read_num'  已读数 新增前
     *          'comment_num'  评论数 新增前
     *      ]
     * @param int $changeType 更新类型 1=>已读数 2=>评论数
     * @param int $inc 新增数
     * @throws \Exception
     */
    public function changeArticleInfo(array $articleInfo, int $changeType, int $inc = 1): void
    {
        $cacheKey = 'astro_fortune_article:change_num:' . $articleInfo['id'];

        $num = Cache::inc($cacheKey);
        $changeTypeCacheKey = [
            1 => 'read_num',
            2 => 'comment_num',
        ];
        // 更新缓存
        $articleInfo[$changeTypeCacheKey[$changeType]] = $articleInfo[$changeTypeCacheKey[$changeType]] + $inc;
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $articleInfo['id'])->setCache([$changeTypeCacheKey[$changeType] => $articleInfo[$changeTypeCacheKey[$changeType]]]);

        $updateStep = 1;    //更新数据库 频率
        if ($num >= $updateStep)
        {
            $this->where(['id' => $articleInfo['id']])->update([
                'read_num' => $articleInfo['read_num'],
                'comment_num' => $articleInfo['comment_num'],
            ]);

            Cache::set($cacheKey, 0, 604800); //7天有效期
        }
    }

    /**
     * 星运变动 动态数据 重组
     * @param int $uid
     * @param array $data
     * @return array
     */
    public function astrFortuneArticleDataResert(int $uid, array $data):array
    {
        $articlePages['data'] = $this->dataInit($data);
        $ids = array_column($articlePages['data'], 'id');
        $astrCommunityArticleZanModel = new Zl2AstrFortuneArticleZan();

        $zanData = $uid > 0 ? $astrCommunityArticleZanModel->getZan($uid, $ids) : [];

        if ($zanData)
        {
            if (count($ids) === 1 && !is_array($zanData))
            {
                $zanData = [current($ids) => (int)$zanData];
            }
        }

        $resData = [];
        $userInfoList = [];
        foreach ($articlePages['data'] as $datum)
        {
            $userDes = '小行星神秘人';
            if (isset($userInfoList[$datum['uid']]))
            {
                $userDes = $userInfoList[$datum['uid']]['user_des'];
                $nickname = $userInfoList[$datum['uid']]['nickname'];
                $avatar = $userInfoList[$datum['uid']]['avatar'];
            } else
            {
                $userInfo = (new User())->getUserinfo(['id' => $datum['uid']]);
                if ($userInfo['rid'])
                {
                    $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                    if ($recode)
                    {
                        $utilModel = new Util();
                        $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                    }
                }
                $nickname = $userInfo['nickname'];
                $avatar = $userInfo['avatar'];
                $userInfoList[$datum['uid']] = [
                    'nickname' => $nickname,
                    'avatar' => $avatar,
                    'user_des' => $userDes
                ];
            }
            $adorn = Util::getUserAdorn($datum['uid']);

            $commentBase = $datum['extend']['comment_base'] ?? 0;
            $zanBase = $datum['extend']['zan_base'] ?? 0;
            $zan2Base = $datum['extend']['zan2_base'] ?? 0;

            $resData[] = [
                'id' => $datum['id'],
                'nickname' => $nickname,
                'avatar' => $avatar,
                'create_time' => Util::timeToStr($datum['create_time']),
                'user_des' => $userDes,
                'title' => $datum['title'],
                'comment_num' => $datum['comment_num'] + $commentBase,
                'photo_list' => $datum['photos'],
                'isself' => $datum['uid'] === $uid ? 1 : 0,
                'avatar_adorn' => $adorn['avatar_adorn'],
                'tag' => $adorn['tag'],
                'badge' => $adorn['badge'],
                'zan_num' => $datum['zan_num'] + $zanBase,
                'zan_num2' => $datum['zan_num2'] + $zan2Base,
                'is_zan' => isset($zanData[$datum['id']]) && $zanData[$datum['id']] ? (int)$zanData[$datum['id']] : 0,  // 赞同｜反对
            ];
        }

        return $resData;
    }
}
